const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const User = require('./User');
const Question = require('./Question');

class QuestionCollection extends Model { }
QuestionCollection.init(
  {
    user_id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      references: {
        model: User,
        key: 'user_id'
      }
    },
    question_id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      references: {
        model: Question,
        key: 'id'
      }
    },
    collect_time: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      comment: '收藏时间'
    }
  },
  {
    sequelize,
    modelName: 'QuestionCollection',
    tableName: 'question_collection',
    timestamps: false,
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['question_id']
      }
    ]
  }
);

// 建立关联关系
QuestionCollection.belongsTo(User, {
  foreignKey: 'user_id',
  targetKey: 'user_id',
  as: 'user'
});

QuestionCollection.belongsTo(Question, {
  foreignKey: 'question_id',
  targetKey: 'id',
  as: 'question'
});

// 在 User 模型中添加关联
User.hasMany(QuestionCollection, {
  foreignKey: 'user_id',
  sourceKey: 'user_id',
  as: 'collections'
});

// 在 Question 模型中添加关联
Question.hasMany(QuestionCollection, {
  foreignKey: 'question_id',
  sourceKey: 'id',
  as: 'collections'
});

module.exports = QuestionCollection;